package com.zzyl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.NursingPlanDto;
import com.zzyl.dto.NursingProjectPlanDto;
import com.zzyl.entity.NursingPlan;
import com.zzyl.mapper.NursingPlanMapper;
import com.zzyl.mapper.NursingProjectPlanMapper;
import com.zzyl.service.NursingPlanService;
import com.zzyl.vo.NursingPlanVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class NursingPlanServiceImpl  implements NursingPlanService {
  @Autowired
  private NursingPlanMapper nursingPlanMapper;
  @Autowired
  private NursingProjectPlanMapper nursingProjectPlanMapper;


  @Override
  public List<NursingPlanVo> listAll() {
    return nursingPlanMapper.listAll();
  }

  @Override
  public PageResponse<NursingPlanVo> search(Integer pageNum, Integer pageSize, String name, Integer status) {
    PageHelper.startPage(pageNum, pageSize);
    Page<NursingPlan> nursingPlanPage = nursingPlanMapper.selectByPage(name, status);
    PageResponse<NursingPlanVo> planVoPageResponse = PageResponse.of(nursingPlanPage, NursingPlanVo.class);
    return planVoPageResponse;
  }

  @Override
  @Transactional(rollbackFor =Exception.class)
  public void add(NursingPlanDto nursingPlanDto) {
    NursingPlan nursingPlan = new NursingPlan();
    BeanUtils.copyProperties(nursingPlanDto, nursingPlan);
    nursingPlan.setCreateTime(LocalDateTime.now());
    nursingPlan.setCreateBy(1L);
    nursingPlan.setStatus(1);
    nursingPlanMapper.insert(nursingPlan);
    List<NursingProjectPlanDto> projectPlans = nursingPlanDto.getProjectPlans();
    projectPlans.stream().forEach(s-> {
      s.setCreateTime(LocalDateTime.now());
      s.setCreateBy(1L);
      s.setPlanId(nursingPlan.getId());
     });
    nursingProjectPlanMapper.insert(projectPlans);
  }

  @Override
  public NursingPlanVo getById(Long planId) {
    return nursingPlanMapper.getById(planId);
  }

  @Override
  @Transactional
  public void update(NursingPlanDto nursingPlanDto) {
    nursingPlanMapper.update(nursingPlanDto);
    nursingProjectPlanMapper.delete(nursingPlanDto.getId());
    List<NursingProjectPlanDto> projectPlans = nursingPlanDto.getProjectPlans();
    projectPlans.stream().forEach(s-> {
      s.setCreateTime(LocalDateTime.now());
      s.setCreateBy(1L);
      s.setPlanId(nursingPlanDto.getId());
    });
    nursingProjectPlanMapper.insert(projectPlans);
  }

  @Override
  public void isActive(String id, Integer status) {
    nursingPlanMapper.isActive(id,status);
  }

  @Override
  @Transactional
  public void deleteById(String id) {
    nursingPlanMapper.deleteById(id);
    nursingProjectPlanMapper.delete(Long.valueOf(id));
  }
}
